//
//  ConfirmDelAccountView.swift
//  ezyform
//
//  Created by Moennig Q on 8/2/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

class ConfirmDelAccountView: MeModelVCBaseView {
    private lazy var diposeBag = DisposeBag()
    var backToPreClosure: (()->Void)?
    var sendVerificationCodeClosure: (()->Void)?
    var confirmClosure: ((String)->Void)?
    //view
    let backView = UIView()
    let verificationCodeTextfield = TextFieldWithRequiredView()
    lazy var sendBtn: BaseButton = {
       let view = BaseButton()
        view.setTitle(R.string.localizable.send(), for: UIControl.State.normal)
        view.setTitleColor(UIColor(hexStr: "#379657"), for: UIControl.State.normal)
        view.setFont(R.font.interBold(size: 15))
        
        return view
    }()
    let confirmDelAccountBtn = OperationButton(R.string.localizable.confirmDeleteAccount())
    //
    lazy var faildReasonLabel = ContentLabel(R.font.interRegular(size: 13),hexStr: "#ED3E3EFF")
    
    override func setUpviews() {
        backView.backgroundColor = .white
        self.addSubview(backView)
        backView.snp.makeConstraints { make in
            make.top.equalTo(self.topBackView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        //title
        let titleLabel = ContentLabel(hexStr: "#292D3299")
        titleLabel.text =  R.string.localizable.toEnsureYourAccountIsSafePleaseEnterTheEmailVerificationCode()
        titleLabel.textAlignment = .left
        titleLabel.lineBreakMode = .byWordWrapping
        titleLabel.numberOfLines = 0
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.greaterThanOrEqualTo(0)
        }
        //email title
        let emailTitle = ContentLabel()
        emailTitle.text =  R.string.localizable.email()
        backView.addSubview(emailTitle)
        emailTitle.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.left.equalTo(titleLabel)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //email text
        let emailLabel = DIYTextField()
        emailLabel.text =  APPConfig.loginInfo.email
        emailLabel.isEnabled = false
        emailLabel.clearButtonMode = .never
        backView.addSubview(emailLabel)
        emailLabel.snp.makeConstraints { make in
            make.top.equalTo(emailTitle.snp.bottom).offset(12)
            make.left.equalTo(titleLabel)
            make.right.equalTo(-20)
            make.height.equalTo(DIYTextField.height)
        }
        //verification code title
        let verificationCodeTitle = LabelWithRedStarView(R.string.localizable.verificationCode())
        backView.addSubview(verificationCodeTitle)
        verificationCodeTitle.snp.makeConstraints { make in
            make.top.equalTo(emailLabel.snp.bottom).offset(20)
            make.left.equalTo(emailLabel)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //verification code text
        verificationCodeTextfield.textField.clearButtonMode = .never
        backView.addSubview(verificationCodeTextfield)
        verificationCodeTextfield.snp.makeConstraints { make in
            make.top.equalTo(verificationCodeTitle.snp.bottom).offset(12)
            make.left.right.equalTo(emailLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        //send btn
        backView.addSubview(sendBtn)
        sendBtn.snp.makeConstraints { make in
            make.top.equalTo(verificationCodeTextfield)
            make.right.equalTo(verificationCodeTextfield).offset(-8)
            make.height.equalTo(DIYTextField.height)
            make.width.greaterThanOrEqualTo(0)
        }
        //
        backView.addSubview(confirmDelAccountBtn)
        confirmDelAccountBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.height.equalTo(OperationButton.height)
            make.left.right.equalTo(emailLabel)
        }
        confirmDelAccountBtn.isEnabled = false
        verificationCodeTextfield.textField.delegate = self
        sendBtn.addTarget(self, action: #selector(sendBtnClick), for: UIControl.Event.touchUpInside)
        confirmDelAccountBtn.addTarget(self, action: #selector(confirmDelAccountBtnClick), for: UIControl.Event.touchUpInside)
        //MARK: -监听验证码的输入，控制底部按钮的有效性
        verificationCodeTextfield.textField.rx.text.orEmpty.subscribe(onNext: {[weak self] in
            guard let strongSelf = self else { return  }
            if $0.count == 6 {
                strongSelf.confirmDelAccountBtn.enableBtn()
            }else{
                strongSelf.confirmDelAccountBtn.disableBtn()
            }
        }).disposed(by: self.diposeBag)
    }
    func showSuccessView(){
        //隐藏右上角的关闭按钮，和左上角的返回按钮
        self.hideTopOperBtns()
        for view in self.backView.subviews{
            view.removeFromSuperview()
        }
        //success image view
        let successImageView = UIImageView(image: R.image.delete_account_success())
        successImageView.contentMode = .scaleAspectFit
        successImageView.setContentHuggingPriority(.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        successImageView.setContentCompressionResistancePriority(.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        backView.addSubview(successImageView)
        successImageView.snp.makeConstraints { make in
            make.top.left.equalTo(40)
            make.right.equalTo(-40)
            make.height.lessThanOrEqualTo(350)
        }
        
        //faild title label
        let successTitleLabel = ContentLabel(R.font.interBold(size: 18))
        successTitleLabel.text =  R.string.localizable.yourAccountHasBeenDeleted()
        successTitleLabel.textAlignment = .center
        backView.addSubview(successTitleLabel)
        successTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(successImageView.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.greaterThanOrEqualTo(0)
        }
        let okBtn = OperationButton(R.string.localizable.oK())
        backView.addSubview(okBtn)
        okBtn.snp.makeConstraints { make in
            make.top.equalTo(successTitleLabel.snp.bottom).offset(40)
            make.centerX.equalToSuperview()
            make.width.equalTo(240)
            make.height.equalTo(OperationButton.height)
        }
        okBtn.rx.tap.subscribe(onNext: {
            LoginService.logOut()
        }).disposed(by: self.diposeBag)
    }
    func showFaildView(faildReason: String = ""){
        //隐藏右上角的关闭按钮，和左上角的返回按钮
        self.hideTopOperBtns()
        for view in self.backView.subviews{
            view.removeFromSuperview()
        }
        //failed image view
        let failedImageView = UIImageView(image: R.image.delete_account_faild())
        failedImageView.contentMode = .scaleAspectFit
        failedImageView.setContentHuggingPriority(.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        failedImageView.setContentCompressionResistancePriority(.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        backView.addSubview(failedImageView)
        failedImageView.snp.makeConstraints { make in
            make.top.left.equalTo(40)
            make.right.equalTo(-40)
            make.height.lessThanOrEqualTo(350)
        }
        
        //faild title label
        let faildTitleLabel = ContentLabel(R.font.interBold(size: 18))
        faildTitleLabel.text = R.string.localizable.deleteAccountFailed()
        faildTitleLabel.textAlignment = .center
        backView.addSubview(faildTitleLabel)
        faildTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(failedImageView.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //faild tip label
        let faildTipLabel = ContentLabel(R.font.interRegular(size: 13),hexStr: "#292D32B2")
        faildTipLabel.text =  NSLocalizedString("deleteAccount.confirm.faild.descrip", comment: "")
        faildTipLabel.textAlignment = .center
        faildTipLabel.numberOfLines = 0
        backView.addSubview(faildTipLabel)
        faildTipLabel.snp.makeConstraints { make in
            make.top.equalTo(faildTitleLabel.snp.bottom).offset(12)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.greaterThanOrEqualTo(0)
        }
        //faild reason label
        faildReasonLabel.text = faildReason
        faildReasonLabel.textAlignment = .center
        faildReasonLabel.numberOfLines = 0
        backView.addSubview(faildReasonLabel)
        faildReasonLabel.snp.makeConstraints { make in
            make.top.equalTo(faildTipLabel.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.greaterThanOrEqualTo(0)
        }
        let backBtn = OperationButton(R.string.localizable.back())
        backView.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.top.equalTo(faildReasonLabel.snp.bottom).offset(40)
            make.centerX.equalToSuperview()
            make.width.equalTo(240)
            make.height.equalTo(OperationButton.height)
            make.bottom.lessThanOrEqualTo(-20)
        }
        backBtn.rx.tap.subscribe(onNext: {[weak self] in
            self?.backToPreClosure?()
        }).disposed(by: self.diposeBag)
    }
    //MARK: - 隐藏右上角的关闭按钮，和左上角的返回按钮
    private func hideTopOperBtns(){
        self.backToPreBtn.isHidden = true
        self.closeBtn.isHidden = true
    }
    @objc func sendBtnClick(){
        self.endEditing(true)
        self.sendBtn.isEnabled = false
        self.sendVerificationCodeClosure?()
    }
    @objc func confirmDelAccountBtnClick(){
        self.endEditing(true)
        self.confirmClosure?(verificationCodeTextfield.textField.text ?? "")
    }
    func setResendBtnTitle(_ title: String,enabled: Bool){
        if enabled {//显示Resend按钮
            sendBtn.setTitleColor(UIColor(hexStr: "#379657"), for: UIControl.State.normal)
            sendBtn.setTitle(R.string.localizable.resend(), for: UIControl.State.normal)
            sendBtn.setFont(R.font.interBold(size: 15))
            sendBtn.isEnabled = true
        }else{//显示倒计时
            sendBtn.setTitle(title, for: UIControl.State.normal)
            sendBtn.setTitleColor(UIColor(hexStr: "#292D3266"), for: UIControl.State.normal)
            sendBtn.setFont(R.font.interMedium(size: 15))
            sendBtn.isEnabled = false
        }
        
    }
    
    
}
extension ConfirmDelAccountView: UITextFieldDelegate{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == " " {
            return false
        }
        let len = (textField.text?.count ?? 0) + string.count - range.length
        if len <= 6 {
            return true
        } else {
            return false
        }
    }
}
